const Koa = require('koa');
const router = require('koa-router')();
const koa2Req = require('koa2-request')

const app = new Koa();

/*
	请求方式: GET
	Query参数: q
*/
router.get('/search/movies', async (ctx, next) => {
	let {q: keyword} = ctx.request.query

	let option = {
	    url:'https://movie.douban.com/j/subject_suggest', //url
	    qs:{                                                  //参数，注意get和post的参数设置不一样  
	        q: keyword,
	    }
	}

    var res = await koa2Req(option);
    ctx.response.body = res.body;
});

/*
	请求方式: GET
	Query参数: q
*/
router.get('/search/movies2', async (ctx, next) => {
	let {q: keyword} = ctx.request.query

	let movies = [
		{
			"img": "https://img2.doubanio.com/view/photo/s_ratio_poster/public/p2568258113.webp",
			"title": "中国机长",
			"url": "https://movie.douban.com/subject/30295905/?suggest=%E4%B8%AD%E5%9B%BD",
			"id": "30295905"
		},
		{
			"img": "https://img1.doubanio.com/view/photo/s_ratio_poster/public/p1959304567.webp",
			"title": "中国合伙人",
			"url": "https://movie.douban.com/subject/11529526/?suggest=%E4%B8%AD%E5%9B%BD",
			"id": "11529526"
		},
		{
			"img": "https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2243829609.webp",
			"title": "中国通史",
			"url": "https://movie.douban.com/subject/20515991/?suggest=%E4%B8%AD%E5%9B%BD",
			"id": "20515991"
		},
		{
			"img": "https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2239933990.webp",
			"title": "中国城",
			"url": "https://movie.douban.com/subject/25890078/?suggest=%E4%B8%AD%E5%9B%BD",
			"id": "25890078"
		},
		{
			"img": "https://img2.doubanio.com/view/photo/s_ratio_poster/public/p2628416332.webp",
			"title": "中国飞侠",
			"url": "https://movie.douban.com/subject/35225280/?suggest=%E4%B8%AD%E5%9B%BD",
			"id": "35225280"
		},
		{
			"img": "https://img9.doubanio.com/view/celebrity/s_ratio_celebrity/public/p0oP_A-Kvg7Ucel_avatar_uploaded1532184648.44.webp",
			"title": "中国卓郎",
			"url": "https://movie.douban.com/celebrity/1397880/?suggest=%E4%B8%AD%E5%9B%BD",
			"id": "1397880"
		}
	]

    ctx.response.body = movies;
});

app.use(router.routes());

app.listen(8000, err => {
	if (!err){
	  	console.log("服务器启动成功")
	  	console.log("请求豆瓣电影真实数据请访问：http://localhost:8000/search/movies")
	  	console.log("请求豆瓣电影模拟数据请访问：http://localhost:8000/search/movies2")
  	} else {
  		console.log(err);
  	}
});
